import jobLogService, { type PageListReq } from "@/api/services/tool/jobLogService";
import TableDictTag from "@/components/grid/TableDictTag";
import { TableToolbar } from "@/components/grid/TableToolbar";
import useDictionary from "@/hooks/system/useDictionary";
import { t } from "@/locales/i18n";
import { Button, Card, Drawer, Form, Input, Select, Space } from "antd";
import Table, { type ColumnsType } from "antd/es/table";
import { useEffect, useMemo, useState } from "react";
import { toast } from "sonner";
import type { JobLog } from "./entity";

const { TextArea } = Input;

interface JobLogProps {
	jobId?: React.Key;
}

const JobLogPage: React.FC<JobLogProps> = ({ jobId }) => {
	const [loading, setLoading] = useState(false);
	const [queryParams, setQueryParams] = useState<PageListReq>({
		jobId: jobId,
		jobName: undefined,
		jobGroup: undefined,
		invokeTarget: undefined,
		status: undefined,
		page: 1,
		pageSize: 10,
	});
	const [total, setTotal] = useState(0);
	const [list, setList] = useState<JobLog[]>([]);
	const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
	const [tableSize, setTableSize] = useState<"large" | "middle" | "small">("middle");
	const [drawerVisible, setDrawerVisible] = useState(false);
	const [form] = Form.useForm();

	const statusOptions = useDictionary("system_success_fail");

	//动态设置表格高度
	const [tableScrollY, setTableScrollY] = useState(0);
	const PAGE_OFFSET_HEIGHT = 403;
	const updateTableHeight = () => {
		const newHeight = window.innerHeight - PAGE_OFFSET_HEIGHT;
		setTableScrollY(newHeight > 200 ? newHeight : 200); // 保证最小高度
	};
	useEffect(() => {
		updateTableHeight(); // 初始化
		window.addEventListener("resize", updateTableHeight);
		return () => window.removeEventListener("resize", updateTableHeight);
	}, []);

	const columns: ColumnsType<JobLog> = [
		{
			title: "任务名称",
			width: 120,
			key: "jobName",
			dataIndex: "jobName",
		},
		{
			title: "任务组名",
			width: 120,
			key: "jobGroup",
			dataIndex: "jobGroup",
		},
		{
			title: "调用目标字符串",
			width: 120,
			key: "invokeTarget",
			dataIndex: "invokeTarget",
		},
		{
			title: "日志信息",
			width: 120,
			key: "jobMessage",
			dataIndex: "jobMessage",
		},
		{
			title: "执行状态",
			width: 120,
			key: "status",
			dataIndex: "status",
			render: (_, record) => <TableDictTag dictCode="system_success_fail" value={record.status} />,
		},
		{
			title: "操作",
			fixed: "right",
			key: "operation",
			align: "center",
			width: 100,
			render: (_, record) => (
				<Space>
					<Button type="link" onClick={() => handleView(record)}>
						{t("common.view")}
					</Button>
				</Space>
			),
		},
	];

	const [selectedValues, setSelectedValues] = useState<string[]>(() =>
		columns.filter((col) => col.key !== "operation").map((col) => String(col.key!)),
	);

	const filteredColumns = useMemo(() => {
		return [...columns.filter((col) => selectedValues.includes(String(col.key)) || col.key === "operation")].sort(
			(a, b) => {
				const originalIndex = columns.findIndex((c) => c.key === a.key);
				const targetIndex = columns.findIndex((c) => c.key === b.key);
				return originalIndex - targetIndex;
			},
		);
	}, [selectedValues]);

	//加载表格数据
	const fetchPageList = () => {
		setLoading(true);
		jobLogService
			.pageList(queryParams)
			.then((res) => {
				setList(res.records);
				setTotal(res.total);
			})
			.catch((error) => {
				console.log(error);
				toast.error("获取数据失败！", error);
			})
			.finally(() => {
				setLoading(false);
			});
	};

	useEffect(() => {
		fetchPageList();
	}, [queryParams]);

	//选择其他页
	const handlePageChange = (newPage: number, newPageSize: number) => {
		setQueryParams((prev) => ({
			...prev,
			page: newPage,
			pageSize: newPageSize,
		}));
	};

	//触发视图按钮
	const handleView = (jobLog: JobLog) => {
		form.setFieldsValue(jobLog);
		setDrawerVisible(true);
	};

	const handleDrawerClose = () => {
		setDrawerVisible(false);
		form.resetFields();
	};

	return (
		<>
			<Card className="mb-4">
				<Form
					layout="inline"
					onFinish={(values) => {
						setQueryParams((prev) => ({
							...prev,
							...values,
							page: 1,
						}));
					}}
				>
					<Form.Item name="jobName" label="任务名称">
						<Input placeholder="请输入任务名称" allowClear />
					</Form.Item>
					<Form.Item name="jobGroup" label="任务组名">
						<Input placeholder="请输入任务组名" allowClear />
					</Form.Item>
					<Form.Item name="invokeTarget" label="调用目标字符串">
						<Input placeholder="请输入调用目标字符串" allowClear />
					</Form.Item>
					<Form.Item name="status" label="执行状态">
						<Select options={statusOptions} style={{width:150}} allowClear />
					</Form.Item>
					<Form.Item>
						<Button type="primary" htmlType="submit" >
							查询
						</Button>
						<Button
							className="ml-2"
							onClick={() => {
								setQueryParams({ page: 1, pageSize: 10 });
							}}
						>
							重置
						</Button>
					</Form.Item>
				</Form>
			</Card>
			<div className="h-4" />
			<Card>
				<div className="flex justify-between mb-4">
					<TableToolbar
						onRefresh={() => setQueryParams((prev) => ({ ...prev }))}
						onSizeChange={setTableSize}
						columns={columns}
						selectedValues={selectedValues}
						onColumnChange={setSelectedValues}
					/>
				</div>
				<Table
					rowKey="id"
					size={tableSize}
					scroll={{ y: tableScrollY }}
					loading={loading}
					pagination={{
						total,
						current: queryParams.page,
						pageSize: queryParams.pageSize,
						onChange: handlePageChange,
					}}
					columns={filteredColumns}
					dataSource={list}
					rowSelection={{
						type: "checkbox",
						selectedRowKeys: selectedRowKeys,
						onChange: (selectedKeys) => {
							setSelectedRowKeys(selectedKeys as string[]);
						},
					}}
				/>
			</Card>
			<Drawer
				title="定时任务调度日志"
				width={480}
				open={drawerVisible}
				onClose={handleDrawerClose}
				footer={
					<div className="flex justify-end gap-2">
						<Button onClick={handleDrawerClose}>取消</Button>
					</div>
				}
			>
				<Form form={form} labelCol={{ span: 6 }} wrapperCol={{ span: 18 }} disabled={true}>
					<Form.Item name="jobName" label="任务名称">
						<Input placeholder="请输入任务名称" allowClear />
					</Form.Item>
					<Form.Item name="jobGroup" label="任务组名">
						<Input placeholder="请输入任务组名" allowClear />
					</Form.Item>
					<Form.Item name="invokeTarget" label="调用目标字符串">
						<TextArea />
					</Form.Item>
					<Form.Item name="jobMessage" label="日志信息">
						<TextArea />
					</Form.Item>
					<Form.Item name="status" label="执行状态">
						<Select options={statusOptions} allowClear />
					</Form.Item>
					<Form.Item name="exceptionInfo" label="异常信息">
						<TextArea rows={13} />
					</Form.Item>
				</Form>
			</Drawer>
		</>
	);
};

export default JobLogPage;
